<?php 
$PageSecurity = 12;
include_once ('includes/session.inc');
set_time_limit(0);

$timeWait = 40000;
$excelType = 'Excel5'; // default Excel 2003 - Excel5,Excel2007
$isCanUpload = false;
$affectRecord = 0;
$failRecord = 0;
$fails = '-';
$sodongloi = 0;
$dongloi = '';
$sobaikhongco = 0;
$baihatkhongco = '';
$tongsoloi = 0;
$content = array('Bài hát', 'Đang cập nhật...', 'Đã import', 'hoàn thành', 'lỗi', 'dòng', 'Quá trình upload bị lỗi.', 'Vui lòng chọn loại tập tin (*.xls, *.xlsx).');

if ($action == 'import' && !isset($_REQUEST['hiddenPartnerPrice'])) {
    die;
}
$partnerPrice = $_REQUEST['hiddenPartnerPrice'];
$sheetIndex = !isset($_REQUEST['SheetIndex']) ? 0 : $_REQUEST['SheetIndex'];
$startRow = !isset($_REQUEST['StartRow']) ? 2 : $_REQUEST['StartRow'];
$numberCol = !isset($_REQUEST['SongNumberCol']) ? 3 : $_REQUEST['SongNumberCol'];
$importDate = !isset($_REQUEST['hiddenImportDate']) ? date('m/d/Y') : $_REQUEST['hiddenImportDate'];
$partnerId = !isset($_REQUEST['hiddenPartnerId']) ? 2 : $_REQUEST['hiddenPartnerId'];
$partnerName = !isset($_REQUEST['PartnerValue']) ? '' : $_REQUEST['PartnerValue'];
$quantityCol = !isset($_REQUEST['QuantityCol']) ? 7 : $_REQUEST['QuantityCol'];

$uploaddir = 'tmp/imported/';
$currDate = getdate();

$action = isset($_POST['action']) ? $_POST['action'] : 'import';

if ($action == 'getPartner') {
    $result = _single('api/partner')->GetAllPartner($_SESSION['UserID'], $_SESSION['Password']);
	
    $data = '{"success":true';
    $data .= ',"data":[';
    $haveData = false;
    
    while ($row = DB_fetch_array($result)) {
        $haveData = true;
        $data .= sprintf('{"partner_id":"%s","partner_number":"%s","partner_name":"%s"},', $row['partner_id'], $row['partner_number'], $row['partner_name']);
    }
    
    if ($haveData) {
        $data = substr($data, 0, strlen($data) - 1);
    }
    
    $data .= '],"count":"'.json_encode($total).'"}';
    echo $data;
} elseif($action == 'getPartnerPrices'){
    $result = _single('api/partner_prices')->getAllPartnerPricesByPartnerId(DB_escape_string(trim($_POST['partner_id'])));
	
    $data = '{"success":true';
    $data .= ',"data":[';
    $haveData = false;
    
    while ($row = DB_fetch_array($result)) {
        $haveData = true;
        $data .= sprintf('{"id":"%s","price":"%s"},', $row['id'], $row['price']);
    }
    
    if ($haveData) {
        $data = substr($data, 0, strlen($data) - 1);
    }
    
    $data .= '],"count":"'.json_encode($total).'"}';
    echo $data;
} elseif ($action == 'import') {
    if (file_exists($_FILES['fileupload']['tmp_name'])) {
        if ($_FILES['fileupload']['type'] == "application/vnd.ms-excel" || ($_FILES['fileupload']['type'] == "application/x-msexcel") || 
        ($_FILES['fileupload']['type'] == "application/excel")) {
            $nameUploadFile = $currDate['0'].basename($_FILES['fileupload']['name']);
            $isCanUpload = true;
        } else if ($_FILES['fileupload']['type'] == "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet") {
            $nameUploadFile = $currDate['0'].basename($_FILES['fileupload']['name']);
            $isCanUpload = true;
            $excelType = 'Excel2007';
        }
        if ($isCanUpload) {
            if (move_uploaded_file($_FILES['fileupload']['tmp_name'], $uploaddir.$nameUploadFile)) {
                $ajaxProgress = new Api_Ajax();
                
                $objPHPExcel = new Api_Excel($nameUploadFile, $uploaddir, $excelType);
                $objPHPExcel->loadIOFactory();
                $objPHPExcel->setActiveSheet($sheetIndex);
                $numberRow = $objPHPExcel->getRowCount();
                
                if (_single('api/exchange')->DeleteExchange($importDate, $partnerId, $partnerPrice, $_SESSION['UserID'], $_SESSION['Password'])) {
					if(!isset($_SESSION['DefaultPriceOfSong'])){
						$ForceConfigReload = true;
						include($PathPrefix . 'includes/GetConfig.php');
					}				
    				for ($rowIndex = $startRow; $rowIndex <= $numberRow; $rowIndex++) {
		                // time start importing a record
		                $time_start = microtime_float();
						
						$number = trim($objPHPExcel->getCellByColumnAndRow($numberCol, $rowIndex));					
						$quantity = trim($objPHPExcel->getCellByColumnAndRow($quantityCol, $rowIndex));
						$songName = '';
						
						if(!empty($number)){
							$song = _single('api/song')->GetSongByNumber($number, $partnerId, $_SESSION['UserID'], $_SESSION['Password']);
							
							if(sizeof($song) != 0){
								$ExchangeDetails = array(
									'exchange_imported_date' => $importDate,
									'partner_id' => $partnerId,
									'partner_name' => $partnerName,
									'song_id' => $song['song_id'],
									'song_number' => $song['song_number'],
									'song_name' => $song['song_name'],
									'singer_id' => $song['singer_id'],
									'singer_name' => $song['singer_name'],
									'song_singer_sing' => $song['song_singer_sing'],
									'composer_id' => $song['composer_id'],
									'composer_name' => $song['composer_name'],
									'exchange_price' => $partnerPrice,
									'exchange_quantity' => $quantity,
									'song_singer_authority' => $song['song_singer_authority'],
									'song_composer_authority' => $song['song_composer_authority'],
									'song_release_authority' => $song['song_release_authority'],
									'created_date' => date('m/d/Y'),
									'created_by' => $_SESSION['UserID'],
									'updated_date' => date('m/d/Y'),
									'updated_by' => $_SESSION['UserID']);
																
								$Result = _single('api/exchange')->InsertExchange($ExchangeDetails, $_SESSION['UserID'], $_SESSION['Password']);
								if(sizeof($Result) == 0){
									$affectRecord++;
									$songName = $song['song_name'];
								}else{
									$tongsoloi++;
									$fails .= $number.'-';
								}
							}else{
								$SongDetails = array(									
									'song_number' => $number,
									'song_price' => $_SESSION['DefaultPriceOfSong'],
									'updated_date' => date('m/d/Y'),
									'updated_by' => $_SESSION['UserID']);
								$song = _single('api/song_notlist')->GetSongByNumber($number, $partnerId, $_SESSION['UserID'], $_SESSION['Password']);
								
								if(empty($song)){
									$SongDetails['created_date'] = date('Y-m-d');
									$SongDetails['created_by'] = $_SESSION['UserID'];
									$SongDetails['partner_id'] = $partnerId;
									
									$Result = _single('api/song_notlist')->InsertSong($SongDetails, $partnerId, $_SESSION['UserID'], $_SESSION['Password']);									
								}
									
								$tongsoloi++;
								$sobaikhongco++;
								$baihatkhongco .= $number.'-';
							}						
						}else{
							$sodongloi++;
							$tongsoloi++;
							$dongloi .= $rowIndex.'-';
						}
											
		                $msgTitle = "$content[0]: $number - $songName - $quantity";
		                $ajaxProgress->advance(($rowIndex + 1) / $numberRow, "$content[1] $rowIndex/$numberRow", $msgTitle);
		                // time delay
		                $time_end = microtime_float();
		                $time = ($time_end - $time_start) * 1000000; // convert second into milisecond
		                if ($time < $timeWait)
		                    usleep($timeWait - $time);
		            }
					$ajaxProgress = null;
	                echo '{success:true, msg:'.json_encode(
						array(
							'content'=>"$content[2] $content[3]: $affectRecord - $content[4] $content[5] : $tongsoloi",
							'affectRecord'=>"$affectRecord",
							'tongsoloi'=>"$tongsoloi",
							'sodongloi'=>"$sodongloi",
							'dongloi'=>"$dongloi",
							'sobaikhongco'=>"$sobaikhongco",
							'baihatkhongco'=>"$baihatkhongco"
						)
					).'}';
	                exit;            
                }else{
                	echo '{success:false, msg:'.json_encode('Đã xuất hiện lỗi khi xóa dữ liệu sản lượng.').'}';
                	exit;
                }
            } else {
                echo '{success:false, msg:'.json_encode($_FILES['fileupload']['name']).'}';
                exit;
            }
        }
    } else {
        echo '{success:false, msg:'.json_encode($_FILES['fileupload']['name'].' không tồn tại.').'}';
        exit;
    }
}

function microtime_float() {
    list($usec, $sec) = explode(" ", microtime());
    return ((float) $usec + (float) $sec);
}

?>
